﻿CREATE PROCEDURE [dbo].[InputLinesInsertUpdate]
	@DocId [int],
	@GoodsId [int],
	@DocQntty [int],
	@SupplierGoodsId [int],
	@ManufacturerPrice [decimal](19, 2),
	@SupplierPrice [decimal](19, 2),
	@SupplierSumNOTAX [decimal](19, 2),
	@ImportMarkup [float],
	@SupplierMarkup [float],
	@BatchNumber [varchar](20),
	@ReadyBefore [smalldatetime],
	@MadeDate [smalldatetime],
	@NDSTax [tinyint],
	@NDSValue [decimal](19, 2),
	@ReestrPrice [decimal](19, 2),
	@ReestrDate [smalldatetime],
	@GTDNumber [varchar](30),
	@CertificateNumber [varchar](80),
	@CertificateDate [smalldatetime],
	@CertificateOrgId [int],
	@RetailMarkup [float],
	@ContragentId [int],
	@ContragentDocDate [smalldatetime],
	@ContragentDocNumber [varchar](20),
	@Note [varchar](250),
	@MD [datetime],
	@MW [varchar](50),
	@Original_Id [int],
	@SetNoCount [bit],
	@Result [tinyint] OUTPUT
WITH EXECUTE AS CALLER
AS
DECLARE @strMsg nvarchar(500), @intRet int, @intErrCode int, @intRowCount int
	SET NOCOUNT ON
	SET ANSI_NULLS OFF
IF 0 != 
(
SELECT TOP 1 DepartmentId FROM PR.DepartmentOptions
)
	BEGIN
		SET @strMsg = 'Накладные можно менять только в Оффисе  !'
		RAISERROR (@strMsg, 11, 1)
		RETURN @intErrCode
	END


IF @CertificateOrgId Is Not Null
BEGIN
	IF NOT EXISTS (SELECT * FROM CA.Contragents WHERE ID = @CertificateOrgId AND ToDelete = 0)
	BEGIN
		IF @@trancount > 0 ROLLBACK TRAN
		SELECT @intErrCode = 201, 
		@strMsg = 'Отсутствует организация с идентификатором ' + cast(@CertificateOrgId as varchar(20)) + ' !'
		RAISERROR (@strMsg, 11, 1)
		RETURN @intErrCode
	END
END

IF NOT EXISTS (SELECT * FROM CA.Contragents WHERE ID = @ContragentId AND ToDelete = 0)
BEGIN
	IF @@trancount > 0 ROLLBACK TRAN
	SELECT @intErrCode = 202, 
	@strMsg = 'Отсутствует контрагент с идентификатором ' + cast(@ContragentId as varchar(20)) + ' !'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

IF NOT EXISTS (SELECT * FROM CA.GoodsVsContragents WHERE ID = @SupplierGoodsId AND ToDelete = 0)
BEGIN
	IF @@trancount > 0 ROLLBACK TRAN
	SELECT @intErrCode = 203, 
	@strMsg = 'Отсутствует перекодировка с идентификатором ' + cast(@SupplierGoodsId as varchar(20)) + ' !'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

IF NOT EXISTS (SELECT * FROM CA.Goods WHERE ID = @GoodsId AND ToDelete = 0)
BEGIN
	IF @@trancount > 0 ROLLBACK TRAN
	SELECT @intErrCode = 204, 
	@strMsg = 'Отсутствует товар с идентификатором ' + cast(@GoodsId as varchar(20)) + ' !'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

IF EXISTS (SELECT Id FROM CD.InputLines WHERE Id = @Original_Id )
BEGIN --запись УЖЕ существует

	IF EXISTS (SELECT Id FROM CD.InputLines 
		WHERE Id								= @Original_Id 
		AND GoodsId							= @GoodsId
		AND DocQntty						= @DocQntty
		AND SupplierGoodsId			= @SupplierGoodsId
		AND ManufacturerPrice		= @ManufacturerPrice
		AND SupplierPrice				= @SupplierPrice
		AND SupplierSumNOTAX		= @SupplierSumNOTAX
		AND ImportMarkup				= @ImportMarkup
		AND SupplierMarkup			= @SupplierMarkup
		AND BatchNumber					= @BatchNumber
		AND ReadyBefore					= @ReadyBefore
		AND MadeDate						= @MadeDate
		AND NDSTax							= @NDSTax
		AND NDSValue						= @NDSValue
		AND ReestrPrice					= @ReestrPrice
		AND ReestrDate					= @ReestrDate
		AND GTDNumber						= @GTDNumber
		AND CertificateNumber		= @CertificateNumber
		AND CertificateDate			= @CertificateDate
		AND CertificateOrgId		= @CertificateOrgId
		AND RetailMarkup				= @RetailMarkup
		AND ContragentId				= @ContragentId
		AND ContragentDocDate		= @ContragentDocDate
		AND ContragentDocNumber	= @ContragentDocNumber
		AND Note								= @Note )
	BEGIN --запись идентична входным параметрам
		SET @Result = 0
	END ELSE BEGIN --некоторые входные параметры отличаются от соответствующих полей в записи
--обновляем запись
		IF @SetNoCount = 0 SET NOCOUNT OFF
--TODO соответствие SupplierPrice, [RetailMarkup] и RetailPrice ??????????????????????????
		UPDATE CD.InputLines SET 
		[GoodsId]						= @GoodsId, 
		DocQntty						= @DocQntty, 
		[SupplierGoodsId]		= @SupplierGoodsId, 
		[ManufacturerPrice] = @ManufacturerPrice, 
		[SupplierPrice]			= @SupplierPrice, 
		SupplierSumNOTAX		= @SupplierSumNOTAX,
		[ImportMarkup]			= @ImportMarkup, 
		[SupplierMarkup]		= @SupplierMarkup, 
		[BatchNumber]				= @BatchNumber, 
		[ReadyBefore]				= @ReadyBefore, 
		[MadeDate]					= @MadeDate, 
		[NDSTax]						= @NDSTax, 
		[NDSValue]					= @NDSValue, 
		[ReestrPrice]				= @ReestrPrice, 
		[ReestrDate]				= @ReestrDate, 
		[GTDNumber]					= @GTDNumber, 
		[CertificateNumber] = @CertificateNumber, 
		[CertificateDate]		= @CertificateDate, 
		[CertificateOrgId]	= @CertificateOrgId, 
		[RetailMarkup]			= @RetailMarkup,
		ContragentId				= @ContragentId,
		ContragentDocDate		= @ContragentDocDate,
		ContragentDocNumber	= @ContragentDocNumber,
		[Note] = @Note, [MD] = @MD, [MW] = @MW 
		WHERE Id = @Original_Id

		SELECT @intErrCode = @@error, @intRowCount = @@rowcount
		IF @intErrCode <> 0 
		BEGIN
			IF @@trancount > 0 ROLLBACK TRAN
			RETURN @intErrCode
		END
		IF (@intRowCount <> 1)
		BEGIN
			IF @@trancount > 0 ROLLBACK TRAN
			SELECT @intErrCode = 205, 
			@strMsg = 'Запись в таблице приходов с идентификатором ' + cast(@Original_Id as varchar(20)) + ' не обновлена!'
			RAISERROR (@strMsg, 11, 1)
			RETURN @intErrCode
		END

		SET @Result = 1
	END

END ELSE BEGIN --запись ЕЩЁ НЕ существует
--добавляем запись в таблицу
	IF @SetNoCount = 0 SET NOCOUNT OFF

	INSERT INTO CD.InputLines 
	(Id, [DocId], [GoodsId], [SupplierGoodsId], [ManufacturerPrice], [SupplierPrice], SupplierSumNOTAX,
	[ImportMarkup], [SupplierMarkup], 
	[BatchNumber], [ReadyBefore], [MadeDate], [NDSTax], [NDSValue], [ReestrPrice], [ReestrDate], 
	[GTDNumber], [CertificateNumber], [CertificateDate], [CertificateOrgId], 
	[RetailMarkup], DocQntty, ContragentId,  ContragentDocDate, ContragentDocNumber, 
	[Note], [MD], [MW]) 
	VALUES (@Original_Id, @DocId, @GoodsId, @SupplierGoodsId, @ManufacturerPrice, @SupplierPrice, @SupplierSumNOTAX, 
	@ImportMarkup, @SupplierMarkup, 
	@BatchNumber, @ReadyBefore, @MadeDate, @NDSTax, @NDSValue, @ReestrPrice, @ReestrDate, 
	@GTDNumber, @CertificateNumber, @CertificateDate, @CertificateOrgId, 
	@RetailMarkup, @DocQntty, @ContragentId, @ContragentDocDate, @ContragentDocNumber, 
	@Note, @MD, @MW)

	SELECT @intErrCode = @@error, @intRowCount = @@rowcount
	IF @intErrCode <> 0 
	BEGIN
		IF @@trancount > 0 ROLLBACK TRAN
		RETURN @intErrCode
	END
	IF (@intRowCount <> 1)
	BEGIN
		IF @@trancount > 0 ROLLBACK TRAN
		SELECT @intErrCode = 206, 
		@strMsg = 'Запись в таблицу приходов не добавлена!'
		RAISERROR (@strMsg, 11, 1)
		RETURN @intErrCode
	END

	SET @Result = 2
END

RETURN 0
